package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.db.entity.AddressInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.SourceBaseInfo;
import com.block.db.entity.SourcePushResultInfo;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.HongHuaParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HongHuaJieKuanReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        UserDataParam userDataParam = this.getUserDataParam(paramContent);

        // 手机号md5 处理
        String mobileMd5 = new AES(Mode.CBC, Padding.PKCS5Padding, sourceBaseInfo.getApiKey().getBytes(), sourceBaseInfo.getApiSecret().getBytes()).decryptStr(userDataParam.getMobileMd5());
        userDataParam.setMobileMd5(mobileMd5);

        // 获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(userDataParam.getCity());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        HongHuaParam hongHuaParam = JSON.parseObject(paramContent, HongHuaParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContent);
        userDataParam.setOutOrderNo(hongHuaParam.getOrderId());

        // 解析产品信息
        String mobile = new AES(Mode.CBC, Padding.PKCS5Padding, sourceBaseInfo.getApiKey().getBytes(), sourceBaseInfo.getApiSecret().getBytes()).decryptStr(hongHuaParam.getPhone());
        userDataParam.setMobile(mobile);

        String productInfo = new AES(Mode.CBC, Padding.PKCS5Padding, sourceBaseInfo.getApiKey().getBytes(), sourceBaseInfo.getApiSecret().getBytes()).decryptStr(hongHuaParam.getProduct());
        JSONArray jsonArray = JSON.parseArray(productInfo);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Integer productId = jsonObject.getInteger("productId");

        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), String.valueOf(productId));
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {
        /**
         * 参数名称	参数说明
         * productName	产品名称
         * institutionName	商户名称
         * productId	产品 ID
         * minMonth	贷款时间 区间范围 最小
         * maxMonth	贷款时间 区间范围 最大
         * monthUnit	贷款时间单位 (month=月, qi=期）
         * rate	利率
         * rateUnit	利率单位（1日利率/2 月利率/3年利率）
         * logo	产品LOGO
         * minPrice	贷款金额 最小
         * maxPrice	贷款金额 最大
         */

        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", "200");
        returnObject.put("msg", "成功");

        JSONObject dataObject = new JSONObject();

        dataObject.put("productId", Integer.valueOf(pushResultInfo.getOutOrderNo()));
        dataObject.put("productName", merchantBaseInfo.getInfoName());
        dataObject.put("institutionName", merchantBaseInfo.getCompanyName());
        dataObject.put("minMonth", "36");
        dataObject.put("maxMonth", "1");
        dataObject.put("monthUnit", "month");
        dataObject.put("rate", merchantBaseInfo.getMinRate());
        dataObject.put("rateUnit", "3");
        dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
        dataObject.put("minPrice", "1000");
        dataObject.put("maxPrice", merchantBaseInfo.getMaxLoanAmount());

        List<JSONObject> listData = new ArrayList<>();
        listData.add(dataObject);

        returnObject.put("data", listData);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", "500");
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", "200");
        returnObject.put("msg", "成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        HongHuaParam hongHuaParam = JSON.parseObject(paramContent, HongHuaParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setMobileMd5(hongHuaParam.getMd5Phone());
        userDataParam.setMobile(hongHuaParam.getPhone());
        userDataParam.setRealName(hongHuaParam.getName());

        String sex = hongHuaParam.getSex()==0?"1":"2";
        userDataParam.setSex(sex);


        userDataParam.setAge(Integer.valueOf(hongHuaParam.getAge()));
        userDataParam.setCity(hongHuaParam.getCity());

        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        userDataParam.setUserIp("127.0.0.1");

        Integer demandAmount = hongHuaParam.getDemandAmount();
        if (demandAmount < 30000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (demandAmount < 50000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (demandAmount < 100000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (demandAmount < 200000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        Integer houseId = hongHuaParam.getHouseId();
        if (ObjectUtil.equals(houseId, Integer.valueOf(132)) || ObjectUtil.equals(houseId, Integer.valueOf(133))){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }else{
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }

        Integer insureId = hongHuaParam.getInsureId();
        if (ObjectUtil.equals(insureId, Integer.valueOf(147))){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }else if (ObjectUtil.equals(insureId, Integer.valueOf(146))){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());
        }else{
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }

        Integer overdueId = hongHuaParam.getOverdueId();
        if (ObjectUtil.equals(overdueId, Integer.valueOf(122))){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else{
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
        }

        Integer providentId = hongHuaParam.getProvidentId();
        if (ObjectUtil.equals(providentId, Integer.valueOf(153))){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }else if (ObjectUtil.equals(providentId, Integer.valueOf(152))){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else{
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }

        Integer sesameId = hongHuaParam.getSesameId();
        if (ObjectUtil.equals(sesameId, Integer.valueOf(115))){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if (ObjectUtil.equals(sesameId, Integer.valueOf(113))){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (ObjectUtil.equals(sesameId, Integer.valueOf(110))){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }

        Integer socialId = hongHuaParam.getSocialId();
        if (ObjectUtil.equals(socialId, Integer.valueOf(159))){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }else if (ObjectUtil.equals(sesameId, Integer.valueOf(158))){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else{
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }

        Integer vehicleId = hongHuaParam.getVehicleId();
        if (ObjectUtil.equals(vehicleId, Integer.valueOf(140))){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }else if (ObjectUtil.equals(vehicleId, Integer.valueOf(139))){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }else{
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }

        Integer vocationId = hongHuaParam.getVocationId();
        if (ObjectUtil.equals(vocationId, Integer.valueOf(127))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (ObjectUtil.equals(vocationId, Integer.valueOf(128))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (ObjectUtil.equals(vocationId, Integer.valueOf(129))){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }

        Integer loanMonth = hongHuaParam.getLoanMonth();
        if (ObjectUtil.isEmpty(loanMonth)){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
        }else{
            if (ObjectUtil.equals(loanMonth, Integer.valueOf(0))){
                userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
            }else if (ObjectUtil.equals(loanMonth, Integer.valueOf(1))){
                userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt002.getValue());
            }else if (ObjectUtil.equals(loanMonth, Integer.valueOf(2))){
                userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
            }
        }

        return userDataParam;
    }

}
